#import "DynamicViewController.h"
#import "SMViewController.h"
#import "CellStyleDynamic.h"
#import "CellDataModel.h"
#import "CellFrame.h"
#import "MJRefresh.h"
#import "CacheManager.h"
#import "NetWorkManager.h"
#import "DynamicEntity.h"
#import "LXActivity.h"
#import "UserDao.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "ImageMediator.h"
#import "SchoolWorkNoticeViewController.h"
#import "PopUIManager.h"
#import "UIImageView+WebCache.h"
#import "JoinClassViewController.h"
#import "BabyInfoViewController.h"
#import "BabyDetailViewController.h"
#import <MessageUI/MessageUI.h>
#import "MBProgressHUD.h"
#import "MobClick.h"
#import "RelationListViewController.h"
#import "CityViewController.h"
#import "AFAppClient.h"

@interface DynamicViewController ()
    @property (nonatomic, strong) NSMutableArray *statusFrames;
@property BOOL barHidden;
@property UIScrollView *headerScroll;
@property UIPageControl *headerPage;
@property UIView *notips;
@property BOOL is_first;
@property NSUInteger total_babys;
@property UIView *headerView;
@property MBProgressHUD *hud;
@property (nonatomic,retain)NSMutableDictionary *dicData;//需要缓存的数据
@property (nonatomic,retain)NSMutableDictionary *cacheData;//缓存总数据
@property (nonatomic,retain)NSString *currCity;
@end

@implementation DynamicViewController

@synthesize tableView,photos;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [MobClick checkUpdate:@"发现新版本" cancelButtonTitle:@"取消" otherButtonTitles:@"下载并安装"];
    _currCity=@"南京";
    //self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    tableView.delegate = self;
    tableView.dataSource = self;
    firstTimeRefresh = true;
    _is_first = YES;
    
    _barHidden = NO;
    
    [[ImageMediator getInstanse]initDynamicViewController:self];
    
    [self setUpRefreshPlugin];
    [self customView];
    [self addHeaderView];
    [self initNoTips];
    self.statusFrames = [[NSMutableArray alloc]init];
    
}

-(void)initNoTips
{
    _notips = [[UIView alloc]initWithFrame:CGRectMake(0, 240, APP_SCREEN_WIDTH, 100)];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-120)/2, 0, 120, 15)];
    label1.textColor = UIColorMake(45, 45, 45);
    label1.text = @"你还没有班级动态";
    label1.font = [UIFont systemFontOfSize:15];
    label1.textAlignment = NSTextAlignmentCenter;
    [_notips addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-260)/2, 20, 260, 15)];
    label2.textColor = UIColorMake(180, 180, 180);
    label2.text = @"赶紧加入班级就可以看到动态啦！";
    label2.font = [UIFont systemFontOfSize:15];
    label2.textAlignment = NSTextAlignmentCenter;
    [_notips addSubview:label2];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-120)/2, 50, 100, 30)];
    [button setTitle:@"加入班级" forState:UIControlStateNormal];
    [button setTintColor:[UIColor whiteColor]];
    [button setBackgroundColor:UIColorMake(252, 74, 74)];
    [button addTarget:self action:@selector(addClass:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 3.0;
    [_notips addSubview:button];
    [self.view addSubview:_notips];
    _notips.hidden = YES;
}

-(void)addClass:(id)sender
{
    JoinClassViewController *joinClass = [[JoinClassViewController alloc]init];
    BabyInfo *baby = [[UserDao getInstance]getCurrentBaby];
    joinClass.babyid = baby.cid;
    joinClass.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:joinClass animated:YES];
    _barHidden = YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *saveCity =[NSString stringWithFormat:@"%@",[[NSUserDefaults  standardUserDefaults] objectForKey:@"city"]];
   
    if(saveCity && ![saveCity isEqualToString:_currCity]){
        //获取天气数据
        NSDictionary *params = @{@"city":saveCity,@"key":WEATH_KEY};
        [[AFAppClient sharedManager]getWithURL:GET_WEATH_URL withParameters:params success:^(NSDictionary *responseObject) {
                debugLog(responseObject);
        } failure:^(NSError *error) {
                
        }];
    }
    
}

-(void)_initData{
    //加载缓存数据
    NSString *path = [HomeDirectory stringByAppendingString:@"dynamic.plist"];
    NSString *plist = [[NSBundle mainBundle] pathForResource:@"dynamic" ofType:@"plist"];
    _cacheData = [[NSMutableDictionary alloc] initWithContentsOfFile:path] ? [[NSMutableDictionary alloc] initWithContentsOfFile:path] : [[NSMutableDictionary alloc] initWithContentsOfFile:plist];
    _dicData = [NSMutableDictionary dictionaryWithDictionary:_cacheData];
  
}
#pragma mark - DATA
//数据写入缓存
- (void)writeToCachePath:(NSDictionary *)dic {
    
    NSString *path = [HomeDirectory stringByAppendingString:@"avtiveData.plist"];
    //_cacheData = dic;
    [dic writeToFile:path atomically:YES];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
-(void)addHeaderView
{
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 224)];
    UIImageView *background = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 224)];
    [background setImage:[UIImage imageNamed:@"header_bg"]];
    [_headerView addSubview:background];
    
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 195, APP_SCREEN_WIDTH, 30)];
    bottomView.backgroundColor = [[UIColor alloc]initWithRed:0 green:0 blue:0 alpha:.28];
    
    UIButton *addBaby =[[UIButton alloc]initWithFrame:CGRectMake(0, 5, APP_SCREEN_WIDTH/2, 20)];
    [addBaby setTitle:@"添加宝贝" forState:UIControlStateNormal];
    [addBaby setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBaby.titleLabel.font = [UIFont systemFontOfSize:14];
    [addBaby addTarget:self action:@selector(add_baby) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView addSubview:addBaby];
    
    UIButton *inviteFriend = [[UIButton alloc]initWithFrame:CGRectMake(APP_SCREEN_WIDTH/2, 5, APP_SCREEN_WIDTH/2, 20)];
    [inviteFriend setTitle:@"邀请好友" forState:UIControlStateNormal];
    inviteFriend.titleLabel.font = [UIFont systemFontOfSize:14];
    [inviteFriend setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [inviteFriend addTarget:self action:@selector(invite_friend) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:inviteFriend];
    
    UIView *verticalLineView=[[UIView alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH/2, 5, .8, 20)];
    [verticalLineView setBackgroundColor:[UIColor whiteColor]];
    [bottomView addSubview:verticalLineView];
    
    [_headerView addSubview:bottomView];
    
    NSArray *babies = [[UserDao getInstance] getMyBabies];
    
    NSUInteger baby_count = babies.count;
    if(baby_count==0){
        debugLog(@"没有宝宝~~");
    }else{
       
        [self createPages:babies];
    }
    
    
    tableView.tableHeaderView = _headerView;
}

-(void)add_baby
{
    BabyInfoViewController *babyInfo = [[BabyInfoViewController alloc]init];
    babyInfo.add_baby = YES;
    babyInfo.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:babyInfo animated:YES];
    _barHidden=YES;
}

-(void)invite_friend
{
    if([[UserDao getInstance]getCurrentBaby].classid==0){
        [[PopUIManager getInstanse]popAlertView:nil title:@"提示" message:@"您尚未加入班级，请加入" cancelButtonTitle:@"确定"];
        return;
    }
//短信邀请
//    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
//    if([MFMessageComposeViewController canSendText])
//    {
//        controller.body = [NSString stringWithFormat:@"我是%@,我为宝贝在【小康轩家园宝】开通小家啦!快来和我一起关注宝贝的幼儿园生活吧!前往http://www.ibaobeimao.com/jyb.html下载家长版，加入我的家族即可哦!我的家族码是:%@",[[UserDao getInstance]getUserInfo].nickName,[[UserDao getInstance]getUserInfo].fcode];
//        controller.recipients = [NSArray arrayWithObjects: nil];
//        controller.messageComposeDelegate = self;
//        [controller.navigationBar setTintColor:[UIColor whiteColor]];
//        [self presentViewController:controller animated:YES completion:^{
//            
//        }];
//    }
    
    RelationListViewController *rlvc = [[RelationListViewController alloc]init];
    rlvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rlvc animated:YES];
    _barHidden=YES;
    
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    
    switch (result)
    {
        case MessageComposeResultCancelled:
            
            break;
        case MessageComposeResultSent:
        
            break;
        case MessageComposeResultFailed:
            
        
            break;
        default:
            
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)createPages:(NSArray*)babies {
    
    _headerScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 180)];
    
    _headerScroll.backgroundColor = [UIColor clearColor];
    
    [_headerView addSubview:_headerScroll];
    _headerPage = [[UIPageControl alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-60)/2, 174, 60, 10)];
    [_headerPage setNumberOfPages:babies.count];
    [_headerPage addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
 
    [_headerView addSubview:_headerPage];
    
    NSUInteger pages = babies.count;
    _total_babys = pages;
    NSUInteger current_page = 0;
    for (int i = 0; i < pages; i++) {
        BabyInfo *baby = [babies objectAtIndex:i];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.headerScroll.bounds) * i, 0, CGRectGetWidth(self.headerScroll.bounds), CGRectGetHeight(self.headerScroll.bounds))];
        UIImageView *babyAvatar = [[UIImageView alloc]initWithFrame:CGRectMake(APP_SCREEN_WIDTH/2-35, 45, 72, 72)];
        NSString *default_icon = @"";
        if (baby.sex == 1) { //男孩
            default_icon = @"default_avatar";
        }else{ //女孩
            default_icon = @"default_avatar_girl";
        }
        
        [babyAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",AVATAR_HEADER,baby.cavatar]] placeholderImage:[UIImage imageNamed:default_icon]];
        
        
        babyAvatar.userInteractionEnabled = YES;
        babyAvatar.layer.cornerRadius = 36;
        babyAvatar.layer.masksToBounds = YES;
        babyAvatar.tag = baby.cid;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(babyDetail:)];
        [babyAvatar addGestureRecognizer:tap];
        [view addSubview:babyAvatar];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH/2-40, 116, 80, 30)];
        [label setText:baby.cname];
        [label setFont:[UIFont boldSystemFontOfSize:17]];
        [label setTextAlignment:NSTextAlignmentCenter];
         [label setTextColor:[UIColor whiteColor]];
        
        UILabel *classname = [[UILabel alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH/2-160, 141, 320, 20)];
        [classname setText:baby.classname];
        [classname setFont:[UIFont boldSystemFontOfSize:15]];
        [classname setTextAlignment:NSTextAlignmentCenter];
         [classname setTextColor:[UIColor whiteColor]];
     
        [view addSubview:label];
        [view addSubview:classname];
        view.backgroundColor = [UIColor clearColor];
        [_headerScroll addSubview:view];
        if(baby.focusid >0){
            current_page =i;
        }
    }
    _headerScroll.delegate = self;
    _headerScroll.showsHorizontalScrollIndicator = NO;
    _headerScroll.showsVerticalScrollIndicator = NO;
    _headerScroll.decelerationRate = UIScrollViewDecelerationRateFast;
    
    [_headerScroll setContentSize:CGSizeMake(CGRectGetWidth(_headerScroll.bounds) * pages, CGRectGetHeight(_headerScroll.bounds))];
    _headerPage.currentPage = current_page;
    CGRect frame = _headerScroll.frame;
    if(pages == 1){
        _headerPage.hidden = YES;
    }else{
        _headerPage.hidden = NO;
    }
    frame.origin.x = APP_SCREEN_WIDTH * _headerPage.currentPage;
    frame.origin.y = 0;
    [_headerScroll scrollRectToVisible:frame animated:YES];
}

-(void)babyDetail:(id)sender
{
    BabyDetailViewController *detail = [[BabyDetailViewController alloc]init];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    _barHidden=YES;
}

-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self showTopBar];
    
    //UIBarButtonItem *leftItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"left_menu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftViewCallback:)];
    
   UIBarButtonItem *leftItem= [[UIBarButtonItem alloc]initWithTitle:@"南京" style:UIBarButtonItemStylePlain target:self action:@selector(leftViewCallback:)];
    
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationItem.title = @"首页";
    
     //UIBarButtonItem *rightItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"dynamic_scan"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick:)];
   // self.navigationItem.rightBarButtonItem = rightItem;
    
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}

-(void)rightItemClick:(id)sender
{
    
}

 -(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //debugLog(@"%f",tableView.contentOffset.y);
    if(scrollView == _headerScroll){
        
    }else{
        CGFloat y = tableView.contentOffset.y;
        if(y<160){
            [self hideTopBar];
        }else{
            [self showTopBar];
        }
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if(scrollView == _headerScroll){
        CGFloat pageWidth = APP_SCREEN_WIDTH;
        NSInteger page =  floor((_headerScroll.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        
        [_headerPage setCurrentPage:page];
        
        [self pageDidChange];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    /*if(scrollView == _headerScroll){
        CGFloat pageWidth = APP_SCREEN_WIDTH;
        NSInteger page =  floor((_headerScroll.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        
        [_headerPage setCurrentPage:page];
        [self pageDidChange];
    }
     */
}

#pragma mark - IBActions
- (void)changePage:(UIPageControl *)sender {
    _headerPage.currentPage = sender.currentPage;
    [self pageDidChange];
}

-(void)pageDidChange
{
    CGRect frame = _headerScroll.frame;
    frame.origin.x = APP_SCREEN_WIDTH * _headerPage.currentPage;
    frame.origin.y = 0;
    [_headerScroll scrollRectToVisible:frame animated:YES];
    NSArray *babies = [[UserDao getInstance] getMyBabies];
    BabyInfo *curr = [babies objectAtIndex:_headerPage.currentPage];
    [[BabyDao getInstance]setCurrentBaby:curr];
    [self headerRereshing];
}

-(void)showTopBar
{
    
   // [[UINavigationBar appearance] setBarTintColor:UIColorMake(252,74,74)];
    self.navigationController.title = @"首页";
    [self.navigationController.navigationBar
     setTitleTextAttributes:@{NSForegroundColorAttributeName : NavigationTitleColor,
                              NSFontAttributeName:[UIFont systemFontOfSize:20.0]
                              }];
    
    
    
}

-(void)hideTopBar
{
    
    self.navigationItem.title = @"首页";
    /*
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
     */

}

- (void)leftViewCallback:(id)sender {
    //[[SMViewController sharedSMViewController]showLeftView:YES];
    CityViewController *city = [[CityViewController alloc]init];
    city.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:city animated:YES];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return  [ImageMediator getInstanse].photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < [ImageMediator getInstanse].photos.count)
        return [[ImageMediator getInstanse].photos objectAtIndex:index];
    return nil;
}

-(void) stopHeaderRefresh{
    [self.tableView headerEndRefreshing];
}

-(void) stopFooterRefresh{
    [self.tableView footerEndRefreshing];
}

- (void)didClickOnImageIndex:(NSInteger *)imageIndex
{
    if ((int)imageIndex == 0) {  //园务通知
        SchoolWorkNoticeViewController* schoolWorkNotice = [[SchoolWorkNoticeViewController alloc]init];
        schoolWorkNotice.dynamicViewController = self;
        [self.navigationController pushViewController:schoolWorkNotice animated:YES];
        
    }else if ((int)imageIndex == 1){//亲··子作业
    
    }else if ((int)imageIndex == 2){//班级照片
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
        [sheet showInView:self.view];
    }
    NSLog(@"%d",(int)imageIndex);
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ((int)buttonIndex == 0L) {  //拍照
        NSLog(@"pai zhao");
    }else if ((int)buttonIndex == 1){//相册
        NSLog(@"xiang ce");
    }else if ((int)buttonIndex == 2){//取消
        NSLog(@"cancel");
    }
}



//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 取出对应Cell的frame模型,并根据frame的高度设置单元格高度
    CellFrame *cellF = self.statusFrames[indexPath.row];
    return cellF.cellHeight;
}

//设置头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

//设置tableview cell的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.statusFrames.count;
}

//定义每个cell的展示内容
-(UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //使用享元模式，重用cell
    CellStyleDynamic *cell = [CellStyleDynamic cellWithTableView:tableView rowID:indexPath.row];
    // 3.设置数据
    [cell setDataFrame:self.statusFrames[indexPath.row]];
    [cell setAccessoryType:UITableViewCellAccessoryNone];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(void)tableView:(UITableView *)tableViews didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableViews cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
}

/**
 *  集成刷新控件
 */
- (void)setUpRefreshPlugin
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    tableView.headerPullToRefreshText = @"下拉刷新";
    tableView.headerReleaseToRefreshText = @"松开刷新";
    tableView.headerRefreshingText = @"正在刷新...";
    
    tableView.footerPullToRefreshText = @"上拉加载";
    tableView.footerReleaseToRefreshText = @"松开加载";
    tableView.footerRefreshingText = @"正在加载...";
}

- (void)startHeaderRefresh{
    //刷新
    [tableView headerBeginRefreshing];
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
        //网络连通的情况下,将网络的最新数据放进去
        //读取网络数据,将网络数据封装成包
        //下拉刷新获取最新内容，不需要向服务器传递baseid的值。此处传-1
        [self apiGetDynamicMessage:@"new" baseId:@"-1"];
       // [RequestServerAPI apiGetDynamicMessage:self requestType:@"new" baseId:@"-1"];//获取到数据成功，会调用自身方法setDataWithDict.
    }else{
        //没有网络的情况下，加载本地缓存数据
        [self loadLocalData];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//根据服务器传过来的动态数组dict，组织数据
-(void)setNewDataWithDict:(NSDictionary*)dict{
    //图像地址的前串
    NSString* avatar_header = [dict objectForKey:@"avatar_header"];
    NSString* pre_url = [dict objectForKey:@"preurl"];
    
    //组织后的数据放在organize_array中
    NSMutableArray* organize_array = [NSMutableArray arrayWithCapacity:10];
    
    NSArray* list_array = [dict objectForKey:@"data"];
    for (NSDictionary* cellDict in list_array) {
        NSMutableDictionary* organize_dict = [NSMutableDictionary dictionaryWithCapacity:20];
        //发布者图像
        NSString *full_path;
        NSString* avatar = [cellDict objectForKey:@"avatar"];
        if ([avatar isEqual:[NSNull null]]) {
            full_path = @"null";
        }else{
            full_path = [avatar_header stringByAppendingString:avatar];
        }
        [organize_dict setValue:full_path forKey:@"icon"];
        
        //发布者名称
        NSString* name = [cellDict objectForKey:@"name"];
        NSLog(@"发布者名称:%@",name);
        [organize_dict setValue:name forKey:@"nickname"];
        
        //发布动态的序号
        NSString* dyid = [cellDict objectForKey:@"dyid"];
        NSLog(@"动态的序号:%@",dyid);
        [organize_dict setValue:dyid forKey:@"dyid"];
        
        //学校的编号
        NSString* school_id = [cellDict objectForKey:@"schoolid"];
        NSLog(@"school_id:%@",school_id);
        [organize_dict setValue:school_id forKey:@"schoolid"];
        
        //班级的编号
        NSString* class_id = [cellDict objectForKey:@"classid"];
        NSLog(@"class_id:%@",class_id);
        [organize_dict setValue:class_id forKey:@"classid"];
        
        //发布的类型
        NSString* type = [cellDict objectForKey:@"type"];
        NSLog(@"type:%@",type);
        [organize_dict setValue:type forKey:@"type"];
        
        if ([type integerValue] == 5) { //此处代表的是插件作业列表显示
            NSString* time = [cellDict objectForKey:@"time"];
            NSLog(@"time:%@",time);
            [organize_dict setValue:time forKey:@"timestamp"];
            
            NSArray* plugin_array = [cellDict objectForKey:@"plugins"];
            int index = 1;
            for (NSDictionary* plugin_dict in plugin_array) {
                NSString* descp = [plugin_dict objectForKey:@"descp"];
                NSLog(@"descp:%@",descp);
                NSString* scene = [plugin_dict objectForKey:@"scene"];
                NSLog(@"scene:%@",scene);
                NSString* title = [plugin_dict objectForKey:@"title"];
                NSLog(@"title:%@",title);
                
                NSString* fc_id = [plugin_dict objectForKey:@"fc_id"];
                NSLog(@"fc_id:%@",fc_id);
                NSString* sc_id = [plugin_dict objectForKey:@"sc_id"];
                NSLog(@"sc_id:%@",sc_id);
                NSString* pid = [plugin_dict objectForKey:@"pid"];
                NSLog(@"pid:%@",pid);
                
                //此处拼接logo_url串的地址
                NSString* logo_url = [NSString stringWithFormat:@"%@/logo/%@/%@/%@_x.png",pre_url,fc_id,sc_id,pid];
                NSLog(@"Logo_Url : %@",logo_url);
                NSDictionary *plugin_cell = [NSDictionary dictionaryWithObjectsAndKeys:descp,@"descp",fc_id,@"fc_id",pid,@"pid",sc_id,@"sc_id",scene,@"scene",title,@"title",logo_url,@"logo_url", nil];
                NSString* string_key = [NSString stringWithFormat:@"plugin%d",index];
                index++;
                [organize_dict setValue:plugin_cell forKey:string_key];
            }
        }else{
        
            //====================动态的内容单元===================
            NSDictionary * data_dict = [cellDict objectForKey:@"data"];
            //发布者编号
            NSString* author_id = [data_dict objectForKey:@"authorid"];
            NSLog(@"author_id:%@",author_id);
            [organize_dict setValue:author_id forKey:@"authorid"];
        
            //发布内容
            NSString* content = [data_dict objectForKey:@"content"];
            NSLog(@"content:%@",content);
            [organize_dict setValue:content forKey:@"content"];
        
            //动态消息的序列号
            NSString* msg_id = [data_dict objectForKey:@"id"];
            NSLog(@"msg_id:%@",msg_id);
            [organize_dict setValue:msg_id forKey:@"messageid"];
            //发布消息的时间戳
            NSString* time = [data_dict objectForKey:@"time"];
            NSLog(@"time:%@",time);
            [organize_dict setValue:time forKey:@"timestamp"];
            //动态的标题
            NSString* title = [data_dict objectForKey:@"title"];
            NSLog(@"title:%@",title);
            [organize_dict setValue:title forKey:@"title"];
            //
            NSString* admire = [data_dict objectForKey:@"admire"];
            NSLog(@"admire:%@",admire);
            [organize_dict setValue:admire forKey:@"admire"];
            //
            NSString* status = [data_dict objectForKey:@"status"];
            NSLog(@"status:%@",status);
            [organize_dict setValue:status forKey:@"status"];
            //
            NSString* data_type = [data_dict objectForKey:@"type"];
            NSLog(@"data_type:%@",data_type);
            [organize_dict setValue:data_type forKey:@"data_type"];
        
            //=====================动态的图片单元==================
            NSArray* array_pics = [cellDict objectForKey:@"pics"];
            int index = 1;
            for (NSDictionary* dict_pic in array_pics) {
                NSString* src_url = [dict_pic objectForKey:@"srcurl"];
                src_url = [avatar_header stringByAppendingString:src_url];
                NSLog(@"src_url:%@",src_url);
                NSString* image_key_name = [NSString stringWithFormat:@"image%d",index];
                [organize_dict setValue:src_url forKey:image_key_name];
                index++;
                if (index == 10) {//最多9张图
                    break;
                }
            }
        }
        //头插法
        [organize_array insertObject:organize_dict atIndex:0];
        //========================服务器json数据，组织本地化结束===========================
        NSLog(@"=================================================");
    }
    
    //    =================================================
    DynamicEntity *entity = [DynamicEntity getInstanse];
    //清空Array数组
    [entity.deArray removeAllObjects];
    
    //头插法
    for (long i = 0; i<organize_array.count; i++) {
        [entity.deArray insertObject:[organize_array objectAtIndex:i] atIndex:0];
    }
    
    //刷新都会将以前的tableView清空，然后增加新的数据，从服务器上获取的数据
    NSMutableArray *models = [NSMutableArray arrayWithCapacity:10];
    for(NSDictionary *dict in organize_array) {
        //依据数据，创建模型
        CellDataModel *cellModel = [CellDataModel dataWithDict:dict];
        // 根据模型数据创建frame模型
        CellFrame *cellF = [[CellFrame alloc] init];
        
        //根据cellModel设置某个Cell的布局
        [cellF setModel:cellModel];
        
        //将cell的布局存到models中
        [models insertObject:cellF atIndex:0];
    }
    
    self.statusFrames = [[NSMutableArray alloc]init];
    for (CellDataModel *model in models) {
        [self.statusFrames addObject:model];
    }
    
    //网络通畅的情况下，加载更多时，需要将最新获取的数据缓存起来
    //获取更多的时候，将前十条数据缓存到plist文件中
    CacheManager *cacheMgr = [CacheManager getInstanse];
    [cacheMgr writeDataToFile_dynamic:self.statusFrames];
    
    //重新加载动态列表
    [self.tableView reloadData];
}
//===========================================================


//================底部刷新，获取最新动态=========================
- (void)footerRereshing
{
    if([NetWorkManager connectedToNetwork]) {
        //此处的baseid为列表中最后一条数据的baseid值。
        NSString* base_id = [[[DynamicEntity getInstanse].deArray lastObject] objectForKey:@"dyid"];
        NSLog(@"请求的BaseID >>> %@",base_id);
        //当服务器获取到数据时，回调方法setOldDataWithDict
        [self apiGetDynamicMessage:@"old" baseId:base_id];
       // [RequestServerAPI apiGetDynamicMessage:self requestType:@"old" baseId:base_id];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)setOldDataWithDict:(NSDictionary*)dict{
    NSLog(@"______________Server_OLD_Data_Start______________");
    //图像地址的前串
    NSString* avatar_header = [dict objectForKey:@"avatar_header"];
    NSLog(@"avatar_header:%@",avatar_header);
    NSString* pre_url = [dict objectForKey:@"preurl"];
    NSLog(@"pre_url:%@",pre_url);
    
    //组织后的数据放在organize_array中
    NSMutableArray* organize_array = [NSMutableArray arrayWithCapacity:10];
    
    NSArray* list_array = [dict objectForKey:@"data"];
    for (NSDictionary* cellDict in list_array) {
        NSLog(@"server data >>> %@",cellDict);
        NSMutableDictionary* organize_dict = [NSMutableDictionary dictionaryWithCapacity:20];
        //发布者图像
        NSString *full_path;
        NSString* avatar = [cellDict objectForKey:@"avatar"];
        if ([avatar isEqual:[NSNull null]]) {
            full_path = @"null";
        }else{
            full_path = [avatar_header stringByAppendingString:avatar];
        }
        [organize_dict setValue:full_path forKey:@"icon"];
        
        //发布者名称
        NSString* name = [cellDict objectForKey:@"name"];
        NSLog(@"发布者名称:%@",name);
        [organize_dict setValue:name forKey:@"nickname"];
        
        //发布动态的序号
        NSString* dyid = [cellDict objectForKey:@"dyid"];
        NSLog(@"动态的序号:%@",dyid);
        [organize_dict setValue:dyid forKey:@"dyid"];
        
        //学校的编号
        NSString* school_id = [cellDict objectForKey:@"schoolid"];
        NSLog(@"school_id:%@",school_id);
        [organize_dict setValue:school_id forKey:@"schoolid"];

        //班级的编号
        NSString* class_id = [cellDict objectForKey:@"classid"];
        NSLog(@"class_id:%@",class_id);
        [organize_dict setValue:class_id forKey:@"classid"];
        
        //发布的类型
        NSString* type = [cellDict objectForKey:@"type"];
        NSLog(@"type:%@",type);
        [organize_dict setValue:type forKey:@"type"];
        
        if ([type integerValue] == 5) { //此处代表的是插件作业列表显示
            NSString* time = [cellDict objectForKey:@"time"];
            NSLog(@"time:%@",time);
            [organize_dict setValue:time forKey:@"timestamp"];
            
            NSArray* plugin_array = [cellDict objectForKey:@"plugins"];
            int index = 1;
            for (NSDictionary* plugin_dict in plugin_array) {
                NSString* descp = [plugin_dict objectForKey:@"descp"];
                NSLog(@"descp:%@",descp);
                NSString* scene = [plugin_dict objectForKey:@"scene"];
                NSLog(@"scene:%@",scene);
                NSString* title = [plugin_dict objectForKey:@"title"];
                NSLog(@"title:%@",title);
                
                NSString* fc_id = [plugin_dict objectForKey:@"fc_id"];
                NSLog(@"fc_id:%@",fc_id);
                NSString* sc_id = [plugin_dict objectForKey:@"sc_id"];
                NSLog(@"sc_id:%@",sc_id);
                NSString* pid = [plugin_dict objectForKey:@"pid"];
                NSLog(@"pid:%@",pid);
                
                //此处拼接logo_url串的地址
                NSString* logo_url = [NSString stringWithFormat:@"%@/logo/%@/%@/%@_x.png",pre_url,fc_id,sc_id,pid];
                NSLog(@"Logo_Url : %@",logo_url);
                NSDictionary *plugin_cell = [NSDictionary dictionaryWithObjectsAndKeys:descp,@"descp",fc_id,@"fc_id",pid,@"pid",sc_id,@"sc_id",scene,@"scene",title,@"title",logo_url,@"logo_url", nil];
                NSString* string_key = [NSString stringWithFormat:@"plugin%d",index];
                index++;
                [organize_dict setValue:plugin_cell forKey:string_key];
            }
        }else{
            //====================动态的内容单元===================
            NSDictionary * data_dict = [cellDict objectForKey:@"data"];
            //发布者编号
            NSString* author_id = [data_dict objectForKey:@"authorid"];
            NSLog(@"author_id:%@",author_id);
            [organize_dict setValue:author_id forKey:@"authorid"];
        
            //发布内容
            NSString* content = [data_dict objectForKey:@"content"];
            NSLog(@"content:%@",content);
            [organize_dict setValue:content forKey:@"content"];
        
            //动态消息的序列号
            NSString* msg_id = [data_dict objectForKey:@"id"];
            NSLog(@"msg_id:%@",msg_id);
            [organize_dict setValue:msg_id forKey:@"messageid"];
            //发布消息的时间戳
            NSString* time = [data_dict objectForKey:@"time"];
            NSLog(@"time:%@",time);
            [organize_dict setValue:time forKey:@"timestamp"];
            //动态的标题
            NSString* title = [data_dict objectForKey:@"title"];
            NSLog(@"title:%@",title);
            [organize_dict setValue:title forKey:@"title"];
            //
            NSString* admire = [data_dict objectForKey:@"admire"];
            NSLog(@"admire:%@",admire);
            [organize_dict setValue:admire forKey:@"admire"];
            //
            NSString* status = [data_dict objectForKey:@"status"];
            NSLog(@"status:%@",status);
            [organize_dict setValue:status forKey:@"status"];
        
            NSString* data_type = [data_dict objectForKey:@"type"];
            NSLog(@"data_type:%@",data_type);
            [organize_dict setValue:data_type forKey:@"data_type"];
            //===================================================
        
            //=====================动态的图片单元==================
            NSArray* array_pics = [cellDict objectForKey:@"pics"];
            int index = 1;
            for (NSDictionary* dict_pic in array_pics) {
                NSString* src_url = [dict_pic objectForKey:@"srcurl"];
                src_url = [avatar_header stringByAppendingString:src_url];
                NSLog(@"src_url:%@",src_url);
                NSString* image_key_name = [NSString stringWithFormat:@"image%d",index];
                [organize_dict setValue:src_url forKey:image_key_name];
                index++;
                if (index == 10) {
                    break;
                }
            }
        }
        //头插法
        [organize_array insertObject:organize_dict atIndex:0];
        //========================服务器json数据，组织本地化结束===========================
        NSLog(@"=================================================");
    }
    
    DynamicEntity *entity = [DynamicEntity getInstanse];
    
    //尾部插入元素
    int arr_count = (int)organize_array.count;
    for (int i = (arr_count - 1); i >= 0; i--) {
        [entity.deArray addObject:[organize_array objectAtIndex:i]];
    }
    
    NSMutableArray *models = [NSMutableArray arrayWithArray:self.statusFrames];
    for (int i = (arr_count - 1); i >= 0; i--) {
        //依据数据，创建模型
        CellDataModel *cellModel = [CellDataModel dataWithDict:[organize_array objectAtIndex:i]];
        // 根据模型数据创建frame模型
        CellFrame *cellF = [[CellFrame alloc] init];
        //将获取到model数据模型给Frame,并计算初始化frame
        [cellF setModel:cellModel];
        
        //将cell的frame存到models中
        [models addObject:cellF];
    }
    self.statusFrames = [models copy];
    
    [self.tableView reloadData];
}
//===========================================================

//加载本地数据
-(void)loadLocalData{
    //初始化本地数据到内存中
    if (_statusFrames == nil) {
        NSMutableArray *dictArray = [[CacheManager getInstanse] readDataFromFile];
        DynamicEntity *entity = [DynamicEntity getInstanse];
        entity.deArray = dictArray;
        
        NSMutableArray *models = [NSMutableArray arrayWithArray:nil];
        for(NSDictionary *dict in dictArray) {
            //依据数据，创建模型
            CellDataModel *cellModel = [CellDataModel dataWithDict:dict];
            
            // 创建Cell单元格的布局
            CellFrame *cellF = [[CellFrame alloc] init];
            
            //根据具体的显示数据，对Cell进行布局
            [cellF setModel:cellModel];
            
            //将cell的frame存到models中
            [models addObject:cellF];
        }
        self.statusFrames = [models copy];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)apiGetDynamicMessage:(NSString*)requestType baseId:(NSString *)base_id{
 
    NSUInteger classid = [[UserDao getInstance]getCurrentBaby].classid;
    if(classid>0){
        _notips.hidden = YES;
    }else{
        debugLog(@"未加入班级");
        _notips.hidden = NO;
        [self stopHeaderRefresh];
        [self stopFooterRefresh];
        [_statusFrames removeAllObjects];
        [self.tableView reloadData];
        return NO;
    }
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = [[NSDictionary alloc]initWithObjectsAndKeys:uid, @"uid", utype, @"utype",[[UserDao getInstance]getAccessToken], @"token", @(classid), @"classid",requestType,@"dir",base_id, @"baseid", nil];
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"USER_GET_DYNAMIC_MSGS";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        if (connectionError) { //连接失败
//            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                NSLog(@"%@",dict);
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    if([[dict objectForKey:@"retCode"]integerValue]==1){
                        if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                            [self setNewDataWithDict:dict];
                        }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                            [self setOldDataWithDict:dict];
                        }
                    }else{
                        [self ShowExclaHud:@"已加载所有动态"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

#pragma mark - MBHub

- (void)showHudComplete:(NSString *)title success:(BOOL)success {
    NSString *name = success ? @"success" : @"excla";
    _hud.dimBackground = NO;
    _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
    _hud.mode = MBProgressHUDModeCustomView;
    if(title.length > 0) {
        _hud.labelText = title;
    }
    [_hud hide:YES afterDelay:1];
}

- (void)ShowExclaHud:(NSString *)title {
    
    if (!_hud) {
        _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    [self showHudComplete:title success:NO];
}

@end
